#include <libpq-fe.h>
#include <iostream>
#include <string>
#include "pgsql.h"
#include <chrono>
#include <fstream>
#include <vector>
#include "table.h"
#include "predicate.h"
#include "tao.h"

using namespace std;

//database-config
const char* hostaddr = "localhost";
const char* port = "5432";
const char* dbname = "tpch01";
const char* user = "postgres";
const char* password = "";


time_t GetCurrentTimeMsec() {
	auto time = chrono::time_point_cast<chrono::milliseconds>(chrono::system_clock::now());
	time_t timestamp = time.time_since_epoch().count();
	return timestamp;
}


void Stringsplit(const string& str, const char split, vector<string>& res)
{
	if (str == "")		return;
	string strs = str + split;
	size_t pos = strs.find(split);

	while (pos != strs.npos)
	{
		string temp = strs.substr(0, pos);
		res.push_back(temp);
		strs = strs.substr(pos + 1, strs.size());
		pos = strs.find(split);
	}
}

PGconn* conn;

int main(int argc,char* argv[]) {
	
	time_t t_begin = GetCurrentTimeMsec();

	PGsql pgsql(hostaddr, port, dbname, user, password);
	
	conn = pgsql.getConn();

	string sqll = "select distinct l_shipmode from lineitem";
	PGresult* res2 = PQexec(conn,sqll.c_str());
	vector<string> groupvalues;
	int nrow = PQntuples(res2);
	for (int i = 0; i < nrow; i++) {
		groupvalues.push_back(PQgetvalue(res2, i, 0));
	}

	cout << "all groups num " << groupvalues.size() << endl;

	for (int i = 0; i < groupvalues.size(); i++) {
		string sql1 = "select l_shipmode,l_extendedprice from lineitem where l_shipmode = '" + groupvalues[i] + "'";
		vector<string> col_names1 = { "l_shipmode","l_extendedprice" };
		Table t1;
		t1.input_data(conn, "lineitem", sql1, col_names1);
		t1.add_tracebit();
		//t1.table_print(10);


		TupleSense ts;
		ts.all_tables.push_back(t1);
		ts.sense_tables.push_back("lineitem");
		ts.computeTupleSense(t1, "l_extendedprice", t1);
		//ts.computeTupleSense(t5, "l_quantity", t1);

	}

	time_t t_end = GetCurrentTimeMsec();

	cout << "[Timecost] timecost : " << (t_end - t_begin) << endl;

	
}

